package com.letv.android.client.album.controller;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import com.letv.android.client.activity.AlbumPlayActivity;
import com.letv.android.client.fragment.AlbumBaseControllerFragment.Style;
import com.letv.android.client.fragment.AlbumFullControllerFragment;
import com.letv.android.client.fragment.AlbumPlayFragment;
import com.letv.android.client.meditor.VideoControllerMeditor;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.business.flow.album.model.AlbumPlayInfo;
import com.letv.business.flow.play.PlayStatisticsUtils;
import com.letv.component.player.LetvMediaPlayerControl;
import com.letv.core.constant.NetworkConstant;
import com.letv.core.constant.PlayConstant;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.NetworkUtils;
import com.letv.core.utils.StringUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.util.DataConstant;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 点播播放过程中刷新进度handler
 *
 * @author zhuqiao
 */
public class AlbumPlayingHandler extends Handler {

    /**
     * 刷新进度
     */
    public static final int HANDLER_TIME = 0x100;
    /**
     * 统计播放时间
     */
    public static final int UPDATE_STATICICS_TIME = 0x101;
    /**
     * 统计阻塞时间
     */
    public static final int UPDATE_STATICICS_BLOCK_TIME = 0x102;
    /**
     * 拖动进度条显示TIP判断
     */
    public static final int HANDLER_RECOMMEND_TIME = 0x103;

    /**
     * 刷新间隔
     */
    private int mHandlerTimeDelayed = 1000;

    private Context mContext;
    private AlbumPlayActivity mActivity;
    private AlbumPlayFragment mPlayFragment;
    // private LoadLayoutFragmentListener mloadListener;

    private AlbumPlayInfo mPlayInfo;

    /** 用户手动点击进度条定时器 **/
    private Timer mBufferTimer;

    private boolean mIsStoped = true;
    private boolean mHasCalledPlayNext = false;
    /** 是否已经调用过stopback **/
    private boolean mHasStopBack = false;

    public AlbumPlayingHandler(Context context, AlbumPlayFragment playFragment) {
        mContext = context;
        mPlayFragment = playFragment;

        if (mPlayFragment == null) {
            throw new NullPointerException("AlbumPlayingHandler param is null!");
        }

        if (mContext instanceof AlbumPlayActivity) {
            mActivity = (AlbumPlayActivity) mContext;
        }
    }

    public void init() {
        LetvMediaPlayerControl videoView = mPlayFragment.getVideoView();
        VideoControllerMeditor controllerMeditor = mPlayFragment.getControllerMeditor();
        if (mActivity == null || videoView == null || controllerMeditor == null ||
                mActivity.getFlow() == null) {
            return;
        }

        mPlayInfo = mActivity.getFlow().getPlayInfo();
        mPlayInfo.currTime = videoView.getCurrentPosition();
        mPlayInfo.totalTime = videoView.getDuration();

        controllerMeditor.initProcess(
                (int) mPlayInfo.totalTime / 1000, (int) mPlayInfo.currTime / 1000, 0);
        controllerMeditor.setSeekbarVisibile(true);
        controllerMeditor.hideAllControllerLayout();
    }

    @Override
    public void handleMessage(Message msg) {
        if (mActivity.getFlow() == null) {
            return;
        }
        mPlayInfo = mActivity.getFlow().getPlayInfo();

        switch (msg.what) {
            case HANDLER_TIME:
                onProgressHandler();
                break;
            case HANDLER_RECOMMEND_TIME:
                LogInfo.log("zhuqiao", "HANDLER_RECOMMEND_TIME");
                if (mActivity.getFlow().isSkip() && mPlayInfo.endTime > 0) {
                    showPlayRecommendTip(msg.arg1, mPlayInfo.endTime);
                } else {
                    showPlayRecommendTip(msg.arg1, mPlayInfo.totalTime / 1000);
                }
                break;
            case UPDATE_STATICICS_TIME:
                updateStaticicsTime();
                break;
            default:
                break;
        }
    }

    // ---------------------- HANDLER_TIME ----------------------

    /**
     * 刷新进度
     */
    private void onProgressHandler() {
        LetvMediaPlayerControl videoView = mPlayFragment.getVideoView();
        VideoControllerMeditor controllerMeditor = mPlayFragment.getControllerMeditor();
        if (mActivity == null || videoView == null || controllerMeditor == null ||
                mActivity.getFlow() == null) {
            return;
        }

        AlbumPlayFlow flow = mActivity.getFlow();
        mPlayInfo = mActivity.getFlow().getPlayInfo();

        long oldTime = mPlayInfo.currTime;
        mPlayInfo.timeElapsed++;
        mPlayInfo.currRealTime = videoView.getCurrentPosition();
        mPlayInfo.currTime = Math.max(0, mPlayInfo.currRealTime);

        if (mContext instanceof AlbumPlayActivity &&
                ((AlbumPlayActivity) mContext).getVipTrailListener() != null) {
            if (((AlbumPlayActivity) mContext).getVipTrailListener().checkVipTrailIsStateEnd()) {
                // 试看结束
                return;
            }
        }

        if (flow.getLaunchMode() == PlayConstant.PLAY_DEFAULT) {
            // 播放本地视频(不包括有下载记录的视频)时，切到小窗要传过去的播放参数
            flow.setLocalSeek(mPlayInfo.currTime / 1000);
        }

        // showPlayRecommendTip(mPlayInfo.currTime, mPlayInfo.endTime);

        // 更新seekbar进度
        int bufferPercentage = (int) (mPlayInfo.totalTime * getBufferPercentage() / 100000);
        controllerMeditor.updateProgress(Style.BOTH, (int) (mPlayInfo.currTime /
                1000), bufferPercentage);

        if (oldTime == mPlayInfo.currTime) {
            logBuffer();
        } else {
            if (mActivity.getLoadListener() != null &&
                    mActivity.getLoadListener().getBlockLogic() != null) {
                mActivity.getLoadListener().getBlockLogic().isOpen = false;
                mActivity.getLoadListener().getBlockLogic().isLoading = false;
            }
            if (mActivity.getFullControllerFragment() != null) {
                mActivity.getFullControllerFragment().setBlockBtnVisibile(false);
            }
            if (mPlayInfo.mHasBuffered) {
                // 视频卡一次就上报一次
                reportWhenBuffer();
            }

            mPlayFragment.closePauseAd();

            // zhuqiao dlna

            mPlayInfo.mIsBuffered = false;
            if (!mPlayInfo.mIsSlipSeekBar) {
                mPlayInfo.mIsUserClickSeekBar = false;
                mPlayInfo.mIsAutoClickSeekBar = true;
                mPlayInfo.mIsAutoClickSeekBarCount = false;
                mPlayInfo.mIsUserClickSeekBarCount = false;
            }

            if (mActivity.getLoadListener() != null &&
                    mActivity.getLoadListener().isLoadingShow()) {
                mActivity.getLoadListener().finish();
            }

            controllerMeditor.onStreamSwitchFinish();

            if (flow.getPlayRecord() != null) {
                flow.getPlayRecord().setPlayedDuration(mPlayInfo.currTime / 1000);
            }

            if (flow.isFirstPlay()) {
                mPlayInfo.playVideoFirstFrameTime = System.currentTimeMillis();
                // mPlayInfo.totalConsumeTime = System.currentTimeMillis() - mPlayInfo.totalConsumeTime;
                flow.setFirstPlay(false);
                if (!UIsUtils.isLandscape(mContext)) {
                    controllerMeditor.setControllerVisibility(View.VISIBLE, true, Style.HALF);
                }
            }
        }

        controllerMeditor.updateProgress(Style.BOTH,
                (int) mPlayInfo.currTime / 1000, bufferPercentage);

        if (flow.isSkip() && mPlayInfo.endTime > 0) {
            // 提前十五秒提示
            if (mPlayInfo.currTime / 1000 + 15 >= mPlayInfo.endTime && mPlayInfo.mIsShowSkipEnd) {
                // 即将跳过片尾
                mPlayInfo.mIsShowSkipEnd = false;
            }
            showPlayRecommendTip(mPlayInfo.currTime, mPlayInfo.endTime);
            if (mPlayInfo.currTime / 1000 >= mPlayInfo.endTime) {// 判断是跳过片尾
                if (flow.getPlayRecord() != null) {
                    flow.getPlayRecord().setPlayedDuration(-1);
                }
                LogInfo.log("zhuqiao", "handler skip called play next");
                playNext();
                return;
            }
        } else {
            showPlayRecommendTip(mPlayInfo.currTime, mPlayInfo.totalTime / 1000);
        }

        /* 用户播放完统计，防止打点不准造成不进行跳级 start by king 2014-04-28* */

        if (mPlayInfo.currTime / 1000 + 60 >= mPlayInfo.totalTime / 1000 &&
                !mPlayInfo.mIsStaticsFinish && mPlayInfo.totalTime != 0) {
            PlayStatisticsUtils.updatePlayDataStatistics(mActivity.getApplicationContext(),mActivity.getFlow(), DataConstant.StaticticsVersion2Constatnt.PlayerAction.FINISH,
                             mPlayInfo.currTime / 1000 - mPlayInfo.totalTime / 1000, false);

            mPlayInfo.mIsStaticsFinish = true;
            mActivity.reportPlayFinishEvent();

        }
        /* 用户播放完统计，防止打点不准造成不进行跳级 end by king 2014-04-28* */
        this.sendEmptyMessageDelayed(HANDLER_TIME, mHandlerTimeDelayed);
    }

    /**
     * 记录卡顿
     */
    private void logBuffer() {
        if (mActivity.getFlow() == null || mPlayFragment.getVideoView() == null) {
            return;
        }

        AlbumPlayFlow flow = mActivity.getFlow();
        mPlayInfo = flow.getPlayInfo();

        if (flow.isDolby() || mPlayFragment.getVideoView().isPlaying() ||
                mPlayFragment.isEnforcementPause() && !flow.isHasAd()) {
            playError();
        }

        flow.setHasAd(false);
        if (!flow.isFirstPlay()) {
            if (!mPlayInfo.mIsBuffered) {
                mPlayInfo.bufferNum++;
                mPlayInfo.mIsBuffered = true;
            }
            mPlayInfo.bufferTime++;

            if (AlbumFullControllerFragment.mIsFromGlsb) {
                // 切换码流卡顿
                logBufferWhenGlsb();
            } else if (mPlayInfo.mIsUserClickSeekBar) {
                // 手动卡顿
                logBufferWhenUserClick();
            } else {
                // 自动卡顿
                logBufferWhenAuto();
            }
        }
    }

    private void playError() {
        if (mActivity.getFlow() == null || mPlayFragment.getVideoView() == null ||
                mPlayFragment.getControllerMeditor() == null) {
            return;
        }
        AlbumPlayFlow flow = mActivity.getFlow();
        mPlayInfo = flow.getPlayInfo();

        boolean isBufferPlayOver = mPlayFragment.getVideoView().getCurrentPosition() >=
                getBufferPercentage() * mPlayFragment.getVideoView().getDuration() / 100;
        if (mPlayInfo.currTime != 0 && isBufferPlayOver &&
                NetworkUtils.getNetworkType(mContext) == NetworkConstant.NETWORK_TYPE_NO_NET) {
            if (!flow.isDownloadFile()) {
                if (flow.getLaunchMode() != PlayConstant.PLAY_DEFAULT) {
                    if (mActivity.getLoadListener() != null) {
                        mActivity.getLoadListener().requestError("", "");
                    }
                }
                // 隐藏试看布局
                if (((AlbumPlayActivity) mContext).getVipTrailListener() != null) {
                    ((AlbumPlayActivity) mContext).getVipTrailListener().hide();
                }

                if (mActivity.getErrorTopController() != null) {
                    mActivity.getErrorTopController().setPlayErrorCode("", true);
                }
                mPlayFragment.getControllerMeditor().setEnable(false);
            }
        } else {
            if (mActivity.getLoadListener() != null && !flow.isFirstPlay()) {
                if (mActivity.getLoadListener().getBlockLogic() != null) {
                    mActivity.getLoadListener().getBlockLogic().isOpen = true;
                }
                mActivity.getLoadListener().loading(true);
            }
        }
    }

    /**
     * 切换码流卡顿
     */
    private void logBufferWhenGlsb() {
        mPlayInfo = mActivity.getFlow().getPlayInfo();
        mPlayInfo.mIsFromGlsb = true;
        mPlayInfo.mHasBuffered = true;
        mPlayInfo.glsbBfTime++;
        mPlayInfo.blockTime++;
    }

    /**
     * 手动卡顿
     */
    private void logBufferWhenUserClick() {
        mPlayInfo = mActivity.getFlow().getPlayInfo();
        buffTimeScheduleCancel();

        if (!mPlayInfo.mIsUserClickSeekBarCount) {
            mPlayInfo.userBfCount++;
            mPlayInfo.mIsUserClickSeekBarCount = true;
        }

        if (mPlayInfo.userBfCount == 1) {
            mPlayInfo.userFirstBfTime = StringUtils.timeClockString("yyyyMMdd_HH:mm:ss");
        }

        mPlayInfo.userBfTime++;
        mPlayInfo.userBfTimeTotal++;
        mPlayInfo.mHasBuffered = true;
        mPlayInfo.mIsFromUser = true;
        mPlayInfo.blockTime++;

        if (mPlayInfo.userBfTime == 1) {
            // mActivity.getFlow().updateBlockDataStatistics(true, mPlayInfo.userBfTime);
        }
    }

    /**
     * 自动卡顿
     */
    private void logBufferWhenAuto() {
        mPlayInfo = mActivity.getFlow().getPlayInfo();

        if (!mPlayInfo.mIsAutoClickSeekBarCount) {
            mPlayInfo.mIsAutoClickSeekBarCount = true;
            mPlayInfo.autofCount++;
        }
        if (mPlayInfo.mIsAutoClickSeekBar && mPlayInfo.mIsAutoClickSeekBarCount) {
            if (mPlayInfo.autofCount == 1) {
                mPlayInfo.autoFirstBfTime = StringUtils.timeClockString("yyyyMMdd_HH:mm:ss");
            }

            mPlayInfo.autoBfTime++;
            mPlayInfo.autoBfTimeTotal++;
            mPlayInfo.mHasBuffered = true;
            mPlayInfo.mIsFromAuto = true;
            mPlayInfo.blockTime++;
        }
        if (mPlayInfo.autoBfTime == 1) {
            // mActivity.getFlow().updateBlockDataStatistics(true, mPlayInfo.autoBfTime);
        }
    }

    /**
     * 视频卡一次就上报一次
     */
    private void reportWhenBuffer() {
        mPlayInfo = mActivity.getFlow().getPlayInfo();

        if (mPlayInfo.mIsFromUser) {
            // mActivity.getFlow().updateBlockDataStatistics(false, mPlayInfo.userBfTime);
            LogInfo.log("zhuqiao", "手动卡顿...userBfTime=" + mPlayInfo.userBfTime);
            mPlayInfo.mHasBuffered = false;
            mPlayInfo.mIsFromUser = false;
            mPlayInfo.userBfTime = 0;
        } else if (mPlayInfo.mIsFromAuto) {
            // mActivity.getFlow().updateBlockDataStatistics(false, mPlayInfo.autoBfTime);
            LogInfo.log("zhuqiao", "自动卡顿...mAutoBfTime=" + mPlayInfo.autoBfTime);
            mPlayInfo.mHasBuffered = false;
            mPlayInfo.mIsFromAuto = false;
            mPlayInfo.autoBfTime = 0;
        } else if (mPlayInfo.mIsFromGlsb) {
            // mActivity.getFlow().updateBlockDataStatistics(false, mPlayInfo.glsbBfTime);
            LogInfo.log("zhuqiao", "切换码流卡顿...mGlsbBfTime=" + mPlayInfo.glsbBfTime);
            mPlayInfo.mHasBuffered = false;
            mPlayInfo.mIsFromGlsb = false;
            mPlayInfo.glsbBfTime = 0;

            if (mBufferTimer != null) {
                mBufferTimer.cancel();
            }
            mBufferTimer = null;

            AlbumFullControllerFragment.mIsFromGlsb = false;
        }
    }

    /**
     * 得到当前缓冲时间点
     */
    public int getBufferPercentage() {
        return (int) (mActivity.getFlow().getPlayInfo().currDuration * 100 /
                (long) mPlayFragment.getVideoView().getDuration());
    }

    /**
     * 开启定时器
     */
    public void buffTimeSchedule() {
        buffTimeScheduleCancel();
        mPlayInfo = mActivity.getFlow().getPlayInfo();

        mBufferTimer = new Timer();
        mPlayInfo.mIsUserClickSeekBar = true;
        mPlayInfo.mIsAutoClickSeekBar = false;
        mPlayInfo.mIsSlipSeekBar = true;
        mBufferTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mPlayInfo.mIsUserClickSeekBar = false;
                mPlayInfo.mIsAutoClickSeekBar = true;
                mPlayInfo.mIsSlipSeekBar = false;
                AlbumFullControllerFragment.mIsFromGlsb = false;
            }
        }, 5000);// 5S
    }

    /**
     * 关闭定时器
     */
    public void buffTimeScheduleCancel() {
        if (mBufferTimer != null) {
            mBufferTimer.cancel();
            mPlayInfo.mIsSlipSeekBar = false;
        }
        mBufferTimer = null;
    }

    // ---------------------- HANDLER_TIME end ----------------------



    private void updateStaticicsTime() {
        mPlayInfo = mActivity.getFlow().getPlayInfo();
        long elapsedDiff = mPlayInfo.timeElapsed - mPlayInfo.lastTimeElapsed;
        if (mPlayInfo.mUpdateCount == 0) {
            if (elapsedDiff < 15) {
                mPlayInfo.mUpdateCount = 0;
                this.sendEmptyMessageDelayed(UPDATE_STATICICS_TIME, (15 - (elapsedDiff)) * 1000);
            } else {

                PlayStatisticsUtils.updatePlayDataStatistics(mActivity.getApplicationContext(),mActivity.getFlow(),
                        DataConstant.StaticticsVersion2Constatnt.PlayerAction.TIME_ACTION, 15, false);

                mPlayInfo.lastTimeElapsed = mPlayInfo.timeElapsed;
                mPlayInfo.mUpdateCount = 1;
                mActivity.sendHeartEvent(15);
                this.sendEmptyMessageDelayed(UPDATE_STATICICS_TIME, 60000);
                // 上报动作22
                if (mPlayInfo.mTotalConsumeTime != 0) {
                    PlayStatisticsUtils.staticticsLoadTimeInfo(mActivity, mActivity.getFlow(), mActivity
                            .getPlayAdListener()
                            .getAdFragment());
                }
            }
        } else if (mPlayInfo.mUpdateCount == 1) {
            if (elapsedDiff < 60) {
                mPlayInfo.mUpdateCount = 1;
                this.sendEmptyMessageDelayed(UPDATE_STATICICS_TIME, (60 - (elapsedDiff)) * 1000);
            } else {

                PlayStatisticsUtils.updatePlayDataStatistics(mActivity.getApplicationContext(),mActivity.getFlow(),
                        DataConstant.StaticticsVersion2Constatnt.PlayerAction.TIME_ACTION, 60, false);

                mPlayInfo.lastTimeElapsed = mPlayInfo.timeElapsed;
                mPlayInfo.mUpdateCount = 2;
                mActivity.sendHeartEvent(60);
                this.sendEmptyMessageDelayed(UPDATE_STATICICS_TIME, 3 * 60000);
                // 上报动作22
                if (mPlayInfo.mTotalConsumeTime != 0) {
                    PlayStatisticsUtils.staticticsLoadTimeInfo(mActivity, mActivity.getFlow(), mActivity
                            .getPlayAdListener()
                            .getAdFragment());
                }
            }
        } else if (mPlayInfo.mUpdateCount == 2) {
            if (elapsedDiff < 180) {
                mPlayInfo.mUpdateCount = 2;
                this.sendEmptyMessageDelayed(UPDATE_STATICICS_TIME, (180 - (elapsedDiff)) * 1000);
            } else {
                if (mPlayInfo.mTotalConsumeTime != 0) {
                    PlayStatisticsUtils.staticticsLoadTimeInfo(mActivity, mActivity.getFlow(), mActivity
                            .getPlayAdListener()
                            .getAdFragment());
                }

                mActivity.sendHeartEvent(180);
                PlayStatisticsUtils.updatePlayDataStatistics(mActivity.getApplicationContext(),mActivity.getFlow(),
                        DataConstant.StaticticsVersion2Constatnt.PlayerAction.TIME_ACTION, 180, false);

                mPlayInfo.lastTimeElapsed = mPlayInfo.timeElapsed;
                mPlayInfo.mUpdateCount = 2;
                this.sendEmptyMessageDelayed(UPDATE_STATICICS_TIME, 3 * 60000);
            }
        }
    }

    /**
     * 开始刷新进度条
     */
    public void startHandlerTime() {
        mIsStoped = false;
        mHasCalledPlayNext = false;
        mHasStopBack = false;
        this.removeMessages(HANDLER_TIME);
        this.sendEmptyMessage(HANDLER_TIME);
        this.removeMessages(UPDATE_STATICICS_TIME);
        this.sendEmptyMessageDelayed(UPDATE_STATICICS_TIME, 15000);
    }

    /**
     * 停止刷新进度条
     */
    public void stopHandlerTime() {
        mIsStoped = true;
        this.removeMessages(HANDLER_TIME);
        this.removeMessages(UPDATE_STATICICS_TIME);
    }

    /**
     * 统计time和end
     */
    public void onStopBack() {
        mPlayInfo = mActivity.getFlow().getPlayInfo();
        mActivity.reportLastHeartEvent();
        if (mHasStopBack) {
            return;
        }
        mActivity.reportPlayCancelEvent();
        mHasStopBack = true;
        if (mPlayInfo.mTotalConsumeTime != 0) {
            PlayStatisticsUtils.staticticsLoadTimeInfo(mActivity, mActivity.getFlow(), mActivity.getPlayAdListener()
                                                                                                .getAdFragment());
        }


        LogInfo.log("jc666", "albumplayinghandler onstopBack totalConsumeTime:" + mPlayInfo.mTotalConsumeTime);
         PlayStatisticsUtils.updatePlayDataStatistics(mActivity.getApplicationContext(),mActivity.getFlow(),DataConstant.StaticticsVersion2Constatnt.PlayerAction.TIME_ACTION,
                (mPlayInfo.timeElapsed - mPlayInfo.lastTimeElapsed), false);
        if (mPlayInfo.mIsBuffered) {// 当视频在卡顿返回时上报一次block
            // mActivity.getFlow().updateBlockDataStatistics(false, mPlayInfo.userBfTime);
        }
        PlayStatisticsUtils.updatePlayDataStatistics(mActivity.getApplicationContext(),mActivity.getFlow(),DataConstant.StaticticsVersion2Constatnt.PlayerAction.END_ACTION,
                -1, false);

        //  没有上报play时，不上报time、end
        if (!mPlayInfo.mIsStatisticsPlay) {
            return;
        }

    }

    private void showPlayRecommendTip(long curTime, long endTime) {
        if (mActivity != null && mActivity.getRecommendController() != null) {
            mActivity.getRecommendController().showPlayRecommendTip(curTime, endTime);
        }
    }

    /**
     * 播放下一集
     */
    public synchronized void playNext() {
        if (mActivity.getPlayAlbumController() != null && !mHasCalledPlayNext) {
            //           取消播放下一集   by 庞朕
            mActivity.getController().finishPlayer();
            return;
            //            LogInfo.log("sguotao", "**********playnext**********");
            //            if (mActivity.mLaunchMode == PlayConstant.LAUNCH_MODE_URI) {
            //                mActivity.getController().finishPlayer();
            //                return;
            //            }
            //            mHasCalledPlayNext = true;
            //            stopHandlerTime();
            //            mActivity.getPlayAlbumController().playNext();
        }
    }

    // -------------------------- get set --------------------------

    public void setHandlerTimeDelayed(int delay) {
        mHandlerTimeDelayed = delay;
    }

    public boolean isStoped() {
        return mIsStoped;
    }

}
